package com.baidu.encrypt.controller;

import com.baidu.encrypt.common.utils.MinioEncryptService;
import com.baidu.encrypt.entity.CustomModel;
import com.baidu.encrypt.entity.ModelServiceInfo;
import com.baidu.encrypt.service.CustomModelService;
import com.baidu.encrypt.service.ModelServiceInfoService;
import com.baidu.encrypt.vo.modelServiceInfo.UpdateStatusVO;
import com.baidu.sggc.audit.extend.AuditExtendContext;
import com.baidu.sggc.audit.extend.FileMessage;
import com.baidu.sggc.audit.extend.GeneralMessage;
import com.baidu.sggc.core.annotation.AuditLog;
import com.baidu.sggc.core.common.R;
import com.baidu.sggc.core.common.utils.MinioUtil;
import com.baidu.sggc.entity.vo.FsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping()
@Tag(name = "模型服务信息")
@CrossOrigin(origins = "*")
public class ModelServiceInfoController {

    @Autowired
    private MinioEncryptService minioService;

    @Autowired
    private ModelServiceInfoService modelServiceInfoService;


    /**
     * 分页查询样本列表
     */
    @GetMapping("/model-service-info/list")
    @Operation(summary = "模型服务列表", description = "分页查询模型服务列表，支持按名称筛选")
    @AuditLog(module = "模型服务管理", auditObject = "模型服务", operation = "listQuery", message = "查询模型服务列表")
    public R<Page<ModelServiceInfo>> list(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String name) {

        // 构建审计日志查询条件
        Map<String, String> condition = new LinkedHashMap<>();
        condition.put("模型服务名称", name);

        Map<String, Object> queryCriteria = new LinkedHashMap<>();
        queryCriteria.put("查询条件", condition);

        Map<String, Object> extendData = new LinkedHashMap<>();
        extendData.put("query_criteria", queryCriteria);
        AuditExtendContext.setExtendData(extendData);

        // 构建查询条件
        QueryWrapper<ModelServiceInfo> wrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            wrapper.like("name", name);
        }

        Page<ModelServiceInfo> resultPage = modelServiceInfoService.page(new Page<>(pageNum, pageSize), wrapper);
        // 解密
        resultPage.getRecords().forEach(item -> {

        });
        return R.ok(resultPage);
    }

    /**
     * 增模型服务
     */
    @PostMapping("/model-service-info/add")
    @Operation(summary = "新增模型服务", description = "新增模型服务信息，支持上传文件（multipart/form-data格式）")
    @AuditLog(module = "模型服务管理", auditObject = "模型服务", operation = "create", message = "新增模型服务")
    public R add(@RequestBody ModelServiceInfo modelServiceInfo) {

        // 设置创建信息
//        String userId = UserContext.getUserId();
        String userId = "xiaofei";
        if (userId != null) {
            modelServiceInfo.setCreatedBy(userId);
            modelServiceInfo.setUpdatedBy(userId);
        }

        modelServiceInfo.setCreatedTime(new Date());
        modelServiceInfo.setUpdatedTime(new Date());
        modelServiceInfo.setStartStopStatus("0");
        boolean result = modelServiceInfoService.save(modelServiceInfo);

        // 构建审计日志信息
        GeneralMessage msg = new GeneralMessage();
        msg.setDataType("自定义模型");
        msg.setDataName(modelServiceInfo.getName());
        msg.setUniqueIdentification(Collections.singletonList(String.valueOf(modelServiceInfo.getId())));
        msg.setOperationNum(1);

        AuditExtendContext.setExtendData(toMap(msg));

        return R.ok(result);
    }

    /**
     * 编辑模型服务
     */
    @PostMapping("/model-service-info/update")
    @Operation(summary = "更新模型服务", description = "更新模型服务信息，支持重新上传文件（multipart/form-data格式）")
    @AuditLog(module = "模型服务管理", auditObject = "模型服务", operation = "update", message = "更新模型服务")
    public R update(@RequestBody ModelServiceInfo modelServiceInfo) {

        boolean result = modelServiceInfoService.updateById(modelServiceInfo);

        // 构建审计日志信息
        GeneralMessage msg = new GeneralMessage();
        msg.setDataType("模型服务");
        msg.setDataName(modelServiceInfo.getName());
        msg.setUniqueIdentification(Collections.singletonList(String.valueOf(modelServiceInfo.getId())));
        msg.setOperationNum(1);

        AuditExtendContext.setExtendData(toMap(msg));
        return R.ok(result);
    }

    /**
     * 修改启停状态
     */
    @PostMapping("/model-service-info/update-status")
    @Operation(summary = "修改启停状态", description = "通过ID修改模型服务启停状态")
    @AuditLog(module = "模型服务管理", auditObject = "模型服务", operation = "update", message = "修改启停状态")
    public R updateStatus(@RequestBody UpdateStatusVO updateStatusVO) {

        GeneralMessage msg = new GeneralMessage();
        msg.setDataType("模型服务");
        msg.setDataName(updateStatusVO.getName());
        msg.setUniqueIdentification(Collections.singletonList(String.valueOf(updateStatusVO.getId())));
        msg.setOperationNum(1);
        AuditExtendContext.setExtendData(toMap(msg));
        ModelServiceInfo modelServiceInfo = new ModelServiceInfo();
        modelServiceInfo.setId(updateStatusVO.getId());
        modelServiceInfo.setStartStopStatus(updateStatusVO.getStartStopStatus());
        boolean result = modelServiceInfoService.updateById(modelServiceInfo);
        return R.ok(result);
    }

    /**
     * 查询模型服务详情
     */
    @GetMapping("/model-service-info/detail/{id}")
    @Operation(summary = "模型服务详情", description = "通过ID查询模型服务详细信息")
    @AuditLog(module = "模型服务管理", auditObject = "模型服务", operation = "detailsQuery", message = "查询模型服务详情")
    public R<ModelServiceInfo> detail(@PathVariable Long id) {
        // 构建审计日志上下文
        Map<String, Object> extendData = new LinkedHashMap<>();
        Map<String, Object> queryCriteria = new LinkedHashMap<>();
        Map<String, Object> condition = new LinkedHashMap<>();
        condition.put("唯一标识", id);
        queryCriteria.put("查询条件", condition);
        extendData.put("query_criteria", queryCriteria);
        AuditExtendContext.setExtendData(extendData);

        ModelServiceInfo modelServiceInfo = modelServiceInfoService.getById(id);
        return R.ok(modelServiceInfo);
    }

    /**
     * 批量删除模型服务
     */
    @DeleteMapping("/model-service-info/batch-delete")
    @Operation(summary = "批量删除模型服务", description = "通过ID列表批量删除模型服务")
    @AuditLog(module = "模型服务管理", auditObject = "模型服务", operation = "delete", message = "批量删除模型服务")
    public R batchDelete(@RequestBody List<Long> ids) {
        // 构建审计日志信息（Java 8适配）
        GeneralMessage msg = new GeneralMessage();
        msg.setDataType("自定义模型");
        msg.setUniqueIdentification(ids.stream()
                .map(String::valueOf)
                .collect(Collectors.toList()));
        msg.setOperationNum(ids.size());
        AuditExtendContext.setExtendData(toMap(msg));

        boolean result = modelServiceInfoService.removeByIds(ids);
        return R.ok(result);
    }


    /**
     * 上传文件接口
     *
     * @param file MultipartFile 文件
     * @return 文件访问 URL
     */
    @Operation(summary = "上传文件", description = "上传文件")
    @PostMapping(value = "/fs/model-service-info/upload", headers = "content-type=multipart/form-data")
    public R<FsVo> uploadFile(@RequestParam("file") MultipartFile file) {
        System.out.println("/fs/upload" + ": " + LocalDateTime.now());

        String fileName = file.getOriginalFilename();

        // 审计扩展字段：FileMessage
        FileMessage msg = new FileMessage();
        Map<String, List<String>> fileMap = new HashMap<>();
        fileMap.put("模型目录", Collections.singletonList(fileName));
        msg.setFileInfo(fileMap);
        AuditExtendContext.setExtendData(toMap(msg));

        return R.ok(minioService.uploadEncrypted(file));
    }

    /**
     * 对象转Map工具方法（适配Java 8）
     */
    private Map<String, Object> toMap(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.convertValue(obj, Map.class);
    }
}